package com.gui.mianshiya.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gui.mianshiya.annotation.AuthCheck;
import com.gui.mianshiya.common.BaseResponse;
import com.gui.mianshiya.common.ErrorCode;
import com.gui.mianshiya.common.ResultUtils;
import com.gui.mianshiya.constant.UserConstant;
import com.gui.mianshiya.exception.BusinessException;
import com.gui.mianshiya.exception.ThrowUtils;
import com.gui.mianshiya.model.dto.multiQuestion.MultiQuestionAddRequest;
import com.gui.mianshiya.model.dto.multiQuestion.MultiQuestionQueryRequest;
import com.gui.mianshiya.model.dto.multiQuestion.MultiQuestionUpdateRequest;
import com.gui.mianshiya.model.dto.question.QuestionAiGenerateRequest;
import com.gui.mianshiya.model.entity.MultiQuestion;
import com.gui.mianshiya.model.entity.User;
import com.gui.mianshiya.service.MultiQuestionService;
import com.gui.mianshiya.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;

/**
 * @Title: MultiQuestionController
 * @Author quit
 * @Package com.gui.mianshiya.controller
 * @Date 2025/5/12 15:30
 * @description:
 */

@RestController
@RequestMapping("/multi")
@Slf4j
public class MultiQuestionController {

    @Resource
    private UserService userService;

    @Resource
    private MultiQuestionService multiQuestionService;

    /**
     *
     * @param multiQuestionQueryRequest 查詢條件
     * @return 分頁結果
     */
    @PostMapping("/list/questionBank")
    public BaseResponse<Page<MultiQuestion>> listQuestion(@RequestBody MultiQuestionQueryRequest multiQuestionQueryRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        multiQuestionQueryRequest.setUserId(loginUser.getId());
        if (multiQuestionQueryRequest == null) {
            return ResultUtils.error(40000, "參數錯誤");
        }
        long current = multiQuestionQueryRequest.getCurrent();
        long size = multiQuestionQueryRequest.getPageSize();
        // 限制爬蟲
        if (size > 20) {
            return ResultUtils.error(40000, "頁面大小超過限制");
        }
        Page<MultiQuestion> questionPage = multiQuestionService.listMultiQuestionByPage(multiQuestionQueryRequest);
        return ResultUtils.success(questionPage);
    }

    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MultiQuestion>> listQuestionByPage(@RequestBody MultiQuestionQueryRequest multiQuestionQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(multiQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);

        long current = multiQuestionQueryRequest.getCurrent();
        long size = multiQuestionQueryRequest.getPageSize();
        // 限制爬蟲
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR, "頁面大小超過限制");

        // 創建查詢條件
        QueryWrapper<MultiQuestion> queryWrapper = new QueryWrapper<>();
        // 根據題目內容模糊查詢
        String question = multiQuestionQueryRequest.getQuestion();
        if (StringUtils.isNotBlank(question)) {
            queryWrapper.like("question", question);
        }
        // 根據題庫ID精確查詢
        Long questionBankId = multiQuestionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            queryWrapper.eq("questionBankId", questionBankId);
        }
        
        // 設置排序
        String sortField = multiQuestionQueryRequest.getSortField();
        String sortOrder = multiQuestionQueryRequest.getSortOrder();
        // 校驗排序字段
        ThrowUtils.throwIf(StringUtils.isNotBlank(sortField) && !sortField.equals("level") && !sortField.equals("createTime"), 
            ErrorCode.PARAMS_ERROR, "排序字段不合法");
        // 設置排序
        if (StringUtils.isNotBlank(sortField)) {
            // 處理前端傳來的 ascend 和 descend
            boolean isAsc = "ascend".equals(sortOrder);
            queryWrapper.orderBy(true, isAsc, sortField);
        } else {
            // 默認按創建時間降序
            queryWrapper.orderByDesc("createTime");
        }
        
        // 執行分頁查詢
        Page<MultiQuestion> questionPage = multiQuestionService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(questionPage);
    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MultiQuestion>> listQuestionVoByPage(@RequestBody MultiQuestionQueryRequest multiQuestionQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(multiQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = multiQuestionQueryRequest.getCurrent();
        long size = multiQuestionQueryRequest.getPageSize();
        // 限制爬蟲
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR, "頁面大小超過限制");
        // 創建查詢條件
        QueryWrapper<MultiQuestion> queryWrapper = new QueryWrapper<>();
        // 根據題目內容模糊查詢
        String question = multiQuestionQueryRequest.getQuestion();
        if (StringUtils.isNotBlank(question)) {
            queryWrapper.like("question", question);
        }
        // 根據題庫ID精確查詢
        Long questionBankId = multiQuestionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            queryWrapper.eq("questionBankId", questionBankId);
        }

        // 設置排序
        String sortField = multiQuestionQueryRequest.getSortField();
        String sortOrder = multiQuestionQueryRequest.getSortOrder();
        // 校驗排序字段
        ThrowUtils.throwIf(StringUtils.isNotBlank(sortField) && !sortField.equals("level") && !sortField.equals("createTime"),
                ErrorCode.PARAMS_ERROR, "排序字段不合法");
        // 設置排序
        if (StringUtils.isNotBlank(sortField)) {
            // 處理前端傳來的 ascend 和 descend
            boolean isAsc = "ascend".equals(sortOrder);
            queryWrapper.orderBy(true, isAsc, sortField);
        } else {
            // 默認按創建時間降序
            queryWrapper.orderByDesc("createTime");
        }

        // 執行分頁查詢
        Page<MultiQuestion> questionPage = multiQuestionService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(questionPage);
    }

    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addMultiQuestion(@RequestBody MultiQuestionAddRequest multiQuestionAddRequest, HttpServletRequest request) {
        if (multiQuestionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MultiQuestion multiQuestion = new MultiQuestion();
        BeanUtils.copyProperties(multiQuestionAddRequest, multiQuestion);
        multiQuestion.setCreateTime(new Date());
        // 參數校驗
        multiQuestionService.validMultiQuestion(multiQuestion, true);
        boolean result = multiQuestionService.save(multiQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(multiQuestion.getId());
    }

    @GetMapping("/del")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> delMultiQuestion(@RequestParam Long multiQuestionId, HttpServletRequest request) {
        boolean b = multiQuestionService.removeById(multiQuestionId);
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMultiQuestion(@RequestBody MultiQuestionUpdateRequest multiQuestionUpdateRequest,
                                                  HttpServletRequest request) {
        if (multiQuestionUpdateRequest == null || multiQuestionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MultiQuestion multiQuestion = new MultiQuestion();
        BeanUtils.copyProperties(multiQuestionUpdateRequest, multiQuestion);
        // 參數校驗
        multiQuestionService.validMultiQuestion(multiQuestion, false);
        long id = multiQuestionUpdateRequest.getId();
        // 判斷是否存在
        MultiQuestion oldMultiQuestion = multiQuestionService.getById(id);
        ThrowUtils.throwIf(oldMultiQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = multiQuestionService.updateById(multiQuestion);
        return ResultUtils.success(result);
    }

    @PostMapping("/ai/generate")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> aiGenerateMultiQuestions(@RequestBody QuestionAiGenerateRequest questionAiGenerateRequest, HttpServletRequest request) {
        int number = questionAiGenerateRequest.getNumber();
        Long questionBankId = questionAiGenerateRequest.getQuestionBankId();
        // 校验参数
        ThrowUtils.throwIf(questionBankId == null, ErrorCode.PARAMS_ERROR,"题库ID不能为空");
        ThrowUtils.throwIf(number <= 0, ErrorCode.PARAMS_ERROR, "题目数量必须大于 0");
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Boolean b =    multiQuestionService.aiGenerateMultiQuestions(number,loginUser,questionBankId);
        return ResultUtils.success(b);
    }
}
